# base_api_detail
# 2024/10/21
# author:www
# baseApi
# 2024/10/19
# author:www
import inspect
import json

import requests

from configs.config import host
from utils.handle_yaml import get_yaml_data


class BaseApi:
    '''
    初始化函数
    1、每个实例都需要操作一次改方法
    '''

    def __init__(self, token=None):
        if token:
            self.header = {'Authorization': 'Bearer ' + token, }
        else:
            self.header = {'Content-Type': 'application/json'}
        try:
            # 通过类名作为键获取对应类的数据，
            # self.__class__  返回当前实例所属的类对象
            # self.__class__.__name__ 获取当前实例所属类的名称，作为字符串
            self.data = get_yaml_data('../data/apiConfig.yaml')[self.__class__.__name__]
            print('调用基类的子类是：', self.__class__.__name__)
        except KeyError:
            print('继承基类的子类名称在yaml文中未找到！！！调用基类的子类是：', self.__class__.__name__)

    '''
    封装请求函数
    '''

    # 形参是请求参数(body),
    # 参数形式：1、params跟在请求后面name=qq&sex=1;2、data;3、json;4、file
    def request_send(self, request_body):
        try:
            # 返回调用者的函数名称：当request_send被谁调用了，就返回调用者的函数名称；
            # 每个接口都会调用request_send方法，则都能获取到调用这的函数名称
            function_name = inspect.stack()[1][3]
            print('调用者的函数名称是：', function_name)
            data = self.data[function_name]
            # print('yaml文件解析后的内容：',data)
            # print(f'yaml文件解析后的内容详情： method:{data['method']},url:{data['url']}')
            print('调用requeset方法的请求body：', request_body, type(request_body))
            # print('调用requeset方法的请求body：', dumps(request_body), type(request_body))
            # print('调用requeset方法的请求header：', self.header)
            # if isinstance(request_body, dict):
            #     response_body = requests.request(method=data['method'], url=f'{host}' + data['url'], json=request_body,
            #                                      headers=self.header)
            # else:
            #     response_body = requests.request(method=data['method'], url=f'{host}' + data['url'], data =json.loads(request_body),
            #                                      headers=self.header)
            response_body = requests.request(method=data['method'], url=f'{host}' + data['url'], json=request_body,
                                             headers=self.header)
            if response_body.status_code == 200:
                return response_body.json()
            else:
                return response_body.text
        except Exception as e:
            print('出错了')
            raise e


class BaseAssert:
    @classmethod  # 使用类名直接调用方法
    def define_assert(cls, actually, expected):
        '''
        捕获断言失败的异常
        :param actually: 实际结果
        :param expected: 期望结果
        :return:
        '''
        try:
            assert actually == expected
        except Exception as e:
            print('断言失败')
            raise e
